ExpertisePortlet = Class.extend({
	init: function()	{
		this.name = "ExpertisePortlet";
	},
	
	onBegin: function()	{
		this.model = {};
		this.registerObserver();
	},
	
	onEnd: function()	{
		this.unregisterObserver();
	},
	
	onReloadPage: function()	{
		this.run();
	},
	
	onExpertiseChanged: function()	{
		this.useCache = false;
		this.run();
		this.useCache = true;
	},
	
	run: function()	{
		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
		var obj = this;
		var id = this.getRequest().getParam('id');
		this.onAjax('ajax', 'get-all-expertises', {'id': id}, 'GET', 
			{'onSuccess': function(ret)	{
				var rsContexts = ret;
				for (var i=0;i<rsContexts.length;i++)	{
					var ctx = rsContexts[i];
					ctx.image = root+ctx.image;
				}
	
				obj.model.expertiseTitle = "Kinh nghiệm";
				obj.model.expertiseContexts = rsContexts;
				obj.getPortletPlaceholder().paintCanvas(obj.render());
			}}, this.useCache, 300000);
	}
}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface).implement(ObserverInterface);

ExpertiseEditPortlet = ExpertisePortlet.extend({
	init: function()	{
		this.name = "ExpertiseEditPortlet";
	}
}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface);

InterestedAreaPortlet = Class.extend({
	init: function()	{
		this.name = "InterestedAreaPortlet";
		this.useCache = true;
	},
	
	onBegin: function()	{
		this.model = {};
		this.registerObserver();
	},
	
	onEnd: function()	{
		this.unregisterObserver();
	},
	
	onInterestedAreaChanged: function()	{
		this.useCache = false;
		this.run();
		this.useCache = true;
	},
	
	run: function()	{
		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
		var obj = this;
		var id = this.getRequest().getParam('id');
		this.onAjax('ajax', 'get-all-interests', {'id': id}, 'GET', 
				{'onSuccess': function(ret)	{
					var rsContexts = ret;
					for (var i=0;i<rsContexts.length;i++)	{
						var ctx = rsContexts[i];
						ctx.image = root+ctx.image;
					}
				
					obj.model.interestTitle = "Lĩnh vực quan tâm";
					obj.model.interestContexts = rsContexts;
					obj.getPortletPlaceholder().paintCanvas(obj.render());
				}}, this.useCache, 300000);
	}
}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface).implement(ObserverInterface);

InterestedAreaEditPortlet = InterestedAreaPortlet.extend({
	init: function()	{
		this.name = "InterestedAreaEditPortlet";
	}
}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface);

//PluginDebugPortlet = Class.extend({
//	init: function()	{
//		this.name = "PluginDebugPortlet";
//	},
//	
//	onBegin: function()	{
//		this.model = {};
//	},
//	
//	run: function()	{
//		var plgManager = SingletonFactory.getInstance(PluginManager);
//		this.model.plugins = new Array();
//		for(var i=0;i<plgManager.getPlugins().length;i++)	{
//			var plg = plgManager.getPlugins()[i];
//			this.model.plugins.push({'name': plg.getName(), 'loaded': plg.isLoaded()});
//		}
//		this.getPortletPlaceholder().drawToCanvas(this.render());
//	}
//}).implement(PortletInterface).implement(RenderInterface);
//
//PortletDebugPortlet = Class.extend({
//	init: function()	{
//		this.name = "PortletDebugPortlet";
//	},
//	
//	onBegin: function()	{
//		this.model = {};
//	},
//	
//	run: function()	{
//		var portletContainer = SingletonFactory.getInstance(PortletContainer);
//		this.model.portlets = new Array();
//		var portlets = portletContainer.getPortlets();
//		for(var i=0;i<portlets.length;i++)	{
//			var portlet = portlets[i];
//			if (portlet == undefined)	{
//				continue;
//			}
//			this.model.portlets.push({'name': portlet.portlet.getName(), 'active': portlet.active, 'position': portlet.position, 'loaded': portlet.loaded});
//		}
//		this.getPortletPlaceholder().drawToCanvas(this.render());
//	}
//}).implement(PortletInterface).implement(RenderInterface);

//QuestionAskedPortlet = Class.extend({
//	init: function()	{
//		this.name = "QuestionAskedPortlet";
//	},
//	
//	onBegin: function()	{
//		this.model = {};
//	},
//	
//	onReloadPage: function()	{
//		this.run();
//	},
//	
//	run: function()	{
//		var obj = this;
//		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
//		//FIXME: (Done) ProfileId must be retrieved from the request parameters
//		var profileId = this.getRequest().getParam('id', undefined);
//		
//		this.onAjax('question', 'list-auth-question-by-target', {'target_id': profileId}, 'GET', 
//				{'onSuccess': function(ret)	{
//					obj.model.questionAskedTitle = "Các câu đã hỏi";
//					obj.model.questions = ret;
//					obj.getPortletPlaceholder().paintCanvas(obj.render());
//				}});
//	}
//}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface);

//OwnAnswerPortlet = QuestionAskedPortlet.extend({
//	init: function()	{
//		this.name = "OwnAnswerPortlet";
//		this.rows = 5;
//		this.curPage = 1;
//	},
//	
//	onReloadPage: function()	{
//		this.run();
//	},
//	
//	run: function()	{
//		var obj = this;
//		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
//		//FIXME: (Done) ProfileId must be retrieved from the request parameters
//		var profileId = this.getRequest().getParam('id', undefined);
//
//		var pagination = this.getRequest().getParam('pagination', 1);
//		this.onAjax('answer', 'list-user-answer', {'id': profileId, 'from': (pagination-1)*this.rows, 'count': this.rows}, 'GET', 
//				{'onSuccess': function(ret)	{
//					obj.model.ownAnswerTitle = "Các câu đã trả lời";
//					obj.model.answers = ret.answers;
//					obj.getPortletPlaceholder().paintCanvas(obj.render());
//					
//					//build pagination
//					var objParam = {};
//					objParam.numDocs = ret.count;
//					objParam.rows = obj.rows;
//					objParam.curPage = pagination;
//					objParam.request = obj.getRequest();
//					objParam.placeholder = obj.requestForEffectiveResource('PaginationLink');
//					var sbj = SingletonFactory.getInstance(Subject);
//					sbj.notifyEvent("FetchPaginationLink", objParam);
//				}});
//	}
//}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface);

//AskQuestionPortlet = Class.extend({
//	init: function()	{
//		this.name = "AskQuestionPortlet";
//		this.selectedTopics = new Array();
//	},
//	
//	onReloadPage: function()	{
//		this.run();
//	},
//	
//	onBegin: function()	{
//		this.model = {};
//		this.registerObserver();
//	},
//	
//	run: function()	{
//		//if the current profile is the current user's profile, hide everything!
//		var properties = SingletonFactory.getInstance(Application).getSystemProperties();
//		var loggedin = properties.get('user.login');
//		if (loggedin == 1)	{
//			var id = properties.get('user.id');
//			var curID = this.getRequest().getParam('id');
//			if (id == curID)	{
//				this.getPortletPlaceholder().paintCanvas('');
//				return;
//			}
//		}
//		var currentProfileName = SingletonFactory.getInstance(Application).getSystemProperties().get('profile.current.name');
//		this.model.optionalMsg = this.getLocalizedText("OptionalMessage");
//		this.model.optionalDetailMsg = this.getLocalizedText("OptionalDetailMessage");
////		if (currentProfileName == undefined)	{
//			this.model.askMsg = this.getLocalizedText("AskMessageMissingTarget");
////		} else {
////			this.model.askMsg = this.getLocalizedMessage("AskMessage", currentProfileName);
////		}
//		this.getPortletPlaceholder().paintCanvas(this.render());
//	},
//	
//	onEnd: function()	{
//		this.unregisterObserver();
//	},
//	
//	onAskTextBoxFocus: function(eventData)	{
//		var input = this.requestForEffectiveResource('TextBox');
//		if ($(input).hasClass('questionTextBox-NonFocus'))	{
//			$(input).removeClass('questionTextBox-NonFocus');
//			$(input).val('');
//		}
//		this.requestForEffectiveResource("Extended").show();
//	},
//	
//	onAskTextBoxBlur: function()	{
//		var input = this.requestForEffectiveResource('TextBox');
//		if ($(input).val().trim() == '')	{
//			$(input).addClass('questionTextBox-NonFocus');
//			$(input).val('Mời bạn nhập câu hỏi');
//		}
//	},
//	
//	onAskQuestionAutocompleteFetched: function(eventData)	{
//		var addTopic = this.requestForEffectiveResource("AddTopic");
//		$(addTopic).show();
//	},
//	
//	// FIXME:
//	onAskQuestionTopicFocus: function(eventData)	{
//		var ui = eventData.ui;
//		var addTopicInputBox = this.requestForEffectiveResource("AddTopicInputBox");
//		$(addTopicInputBox).val(ui.item.label);
//	},
//	
//	onAskQuestionTopicSelect: function(eventData)	{
//		var ui = eventData.ui;
//		var i = 0;
//		var txt = ui.item.label;
//		var value = ui.item.value;
//		
//		var subject = SingletonFactory.getInstance(Subject);
//		subject.notifyEvent('AskQuestionPortletAppend', {'txt': txt, 'value': value});
//	},
//	
//	onAskQuestionPortletAppend: function(eventData)	{
//		var txt = eventData.txt;
//		var value = eventData.value;
//		
//		var topicContainer = this.requestForEffectiveResource("AddTopicContainer");
//		var addTopicInputBox = this.requestForEffectiveResource("AddTopicInputBox");
//		var selectedTopics = new Array();
//		this.selectedTopics = selectedTopics;
//		
//		for( i=0; i<selectedTopics.length;i++ ){
//			if(selectedTopics[i] === value){
//				return;
//			}
//		}
//		var textToken = $("<label>").text(txt).addClass("tokenContent");
//		selectedTopics.push(value);
//		
//		// UI ONLY
//		var span = $("<span>").addClass("uiToken").append(textToken);
//		var a = $("<input>").addClass("btnStl").addClass("delToken").bind("click",function(event){
//				var start = 0;
//				for( start=0; start<selectedTopics.length; start++ ){
//					if(selectedTopics[start] === value){
//						break;
//					}
//				}
//				selectedTopics.splice(start, 1);
//				$(event.target).parent().remove();
//			}).val("X").css("text-align","center").appendTo(span);
//		topicContainer.append(span);
//	},
//	
//	onAskQuestionPortletAddTopic: function(eventData){
////		if (this.autocompleteGenerated == true)
////			return;
//		this.autocompleteGenerated = true;
//		var addTopicInputBox = this.requestForEffectiveResource("AddTopicInputBox"); 
//		//FIXME: data should be loaded only once !addTopicInputBox
//		var eventData = {};
//		eventData.focusCallback = "AskQuestionTopicFocus";
//		eventData.selectCallback = "AskQuestionTopicSelect";
//		eventData.autocompleteObject = addTopicInputBox;
//		eventData.autocompleteSource = "catchword/autocomplete-all-catchwords";
//		eventData.fetchSourceCallback = "AskQuestionAutocompleteFetched";
//		var subject = SingletonFactory.getInstance(Subject);
//		subject.notifyEvent('NeedAutocomplete', eventData);
//	},
//	
//	onAskProfileButtonClick: function(eventData)	{
//		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
//		var question = this.requestForEffectiveResource("TextBox").val();
//		var extended = this.requestForEffectiveResource("TextAreaExtended").val();
//		var obj = this;
//		//FIXME: (Done) profile ID must be retrieved from the request parameters
//		obj.requestForEffectiveResource("QuestionInfo").html("");
//		obj.requestForEffectiveResource("QuestionError").html("");
//		var profileId = this.getRequest().getParam('id', 1);
//		var selectedTopics = null;
//		if(this.selectedTopics.length > 0){
//			selectedTopics = new Array();
//			for( var i=0; i<this.selectedTopics.length; i++ ){
//				selectedTopics.push({"catchword_id":this.selectedTopics[i],"position":0}); 
//			}
//		}
//		this.onAjax('question', 'add-unauth-question', {'target_id': profileId, 'title': question, 'content': extended, 'catch': selectedTopics}, 'POST', 
//				{'onSuccess': function(ret)	{
//					obj.requestForEffectiveResource("TextBox").val("");
//					obj.requestForEffectiveResource("TextAreaExtended").val("");
//					obj.requestForEffectiveResource("Extended").hide();
//					obj.requestForEffectiveResource("AddTopic").hide();
//					obj.requestForEffectiveResource("AddTopicContainer").html("");
//					obj.selectedTopics = new Array();
//					obj.requestForEffectiveResource("QuestionInfo").html(obj.getLocalizedText("AskSuccess"));
//					},
//				'onFailure': function(message)	{
//						obj.requestForEffectiveResource("QuestionError").html(obj.getLocalizedText("AskError"));
//					}});
//	}
//}).implement(PortletInterface).implement(RenderInterface).implement(ObserverInterface).implement(AjaxInterface);

AskNonTargetQuestionPortlet = Class.extend({
	init: function()	{
		this.name = "AskNonTargetQuestionPortlet";
		this.selectedTopics = new Array();
		this.usingFacebox = false;
	},
	
	requestForEffectiveResource: function(targetName){
		if(this.usingFacebox){
			return $("#"+this.name+"-"+targetName);
		}else{
			return this._super.requestForEffectiveResource(targetName);
		}
	},
	
	onMakeNewQuestion: function(eventData)	{
		this.showPortlet(eventData);
	},
	
	showPortlet: function(eventData){
		//console.log("shown");
		var loggedIn = SingletonFactory.getInstance(Application).getSystemProperties().get('user.login');
		if (loggedIn != 1)	{
			var subject = SingletonFactory.getInstance(Subject);
			subject.notifyEvent("NeedLogin", {type: 'AskNonTarget', event: eventData});
		} else {
			this.doShowPortlet(eventData);
		}
	},
	
	onLoginSuccess: function(eventData)	{
		if (eventData.type != 'AskNonTarget')
			return;
		this.doShowPortlet(eventData.event);
	},
	
	// Mar21
	doShowPortlet: function(eventData)	{
		var app = SingletonFactory.getInstance(Application);
		var subject = SingletonFactory.getInstance(Subject);
		this.usingFacebox = true;
		this.selectedPeople = Array();
		this.selectedTopics = Array();
		
		this.model.optionalMsg = $("#"+this.name+"-TextOptionalMessage").html();
		this.model.optionalDetailMsg = $("#"+this.name+"-TextOptionalDetailMessage").html();
		this.model.askMsg = $("#"+this.name+"-TextAskMessage").html();
		this.model.question = eventData.question;
		subject.notifyEvent('ShowPopup', {id: 'AskNonTargetQuestion', title: '<img src="static/css/beta/images/icon/24/question.png" alt="question"/>Đặt câu hỏi', content: this.render()});
		$('#AskNonTargetQuestionPortlet-TextBox').focus();
		var target = this.requestForEffectiveResource('TextAreaExtended');
		subject.notifyEvent('ExpandTextArea', {target: target, min: 30, max: 200});
		
		var profile = eventData.profile;
		if (profile != undefined)	{
			for(var i=0;i<profile.length && i<2;i++)	{
				this.appendPeople({value: profile[i].id, txt: profile[i].name});
			}
		}
		
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('AskNonTargetQuestionPortletFetchAutocomplete');
	},
	
	onAskNonTargetQuestionPortletFetchAutocomplete: function()	{
		var addTopicInputBox = this.requestForEffectiveResource("AddTopicInputBox"); 
		//FIXME: data should be loaded only once !addTopicInputBox
		var eventData = {};
		eventData.selectCallback = "AskNonTargetQuestionTopicSelect";
		eventData.autocompleteObject = addTopicInputBox;
		eventData.autocompleteSource = "ajax/autocomplete-catchwords";
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('NeedAutocomplete', eventData);
		
		var addPeopleInputBox = this.requestForEffectiveResource("AddPeopleInputBox");
		var eventData = {};
		eventData.selectCallback = "AskNonTargetQuestionPeopleSelect";
		eventData.autocompleteObject = addPeopleInputBox;
		eventData.autocompleteSource = "ajax/autocomplete-person";
		eventData.type = "person";
		subject.notifyEvent('NeedAutocomplete', eventData);
	},
	
	appendPeople: function(obj)	{
		var txt = obj.txt;
		var value = obj.value;
		
		var topicContainer = this.requestForEffectiveResource("AddPeopleContainer");
		if (this.selectedPeople == undefined)
			this.selectedPeople = Array();
		if (this.selectedPeople.length >= 2)
			return;
		for( i=0; i<this.selectedPeople.length;i++ ){
			if(this.selectedPeople[i] === value){
				return;
			}
		}
		var textToken = $("<label class='tokenContent'>"+txt+"</label>");
		this.selectedPeople.push(value);
		
		// UI ONLY
		var selectedPeople = this.selectedPeople;
		var span = $("<span>").addClass("uiToken").append(textToken);
		var a = $("<span>").addClass("btnStl").addClass("delToken").bind("click",function(event){
			for( start=0; start<selectedPeople.length; start++ ){
				if(selectedPeople[start] === value){
					break;
				}
			}
			selectedPeople.splice(start, 1);
			$(event.target).parent().remove();
		}).html("X").css("text-align","center").appendTo(span);
		topicContainer.append(span);
	},
	
	onAskNonTargetQuestionPeopleSelect: function(eventData)	{
		var ui = eventData.ui;
		var txt = ui.item.label;
		var value = ui.item.id;
		
		this.appendPeople({value: value, txt: txt});
	},
	
	onBegin: function()	{
		this.model = {};
		this.registerObserver();
	},
	
	run: function()	{
		this.model.optionalMsg = this.getLocalizedText("OptionalMessage");
		this.model.optionalDetailMsg = this.getLocalizedText("OptionalDetailMessage");
		this.model.askMsg = this.getLocalizedText("AskMessage");
		this.getPortletPlaceholder().drawToCanvas(this.render());
	},
	
	onEnd: function()	{
		this.unregisterObserver();
	},
	
	// Chọn topic
	onAskNonTargetQuestionTopicSelect: function(eventData)	{
		var ui = eventData.ui;
		var i = 0;
		var txt = ui.item.label;
		var value = ui.item.id;
		
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('AskNonTargetQuestionPortletAppend', {'txt': txt, 'value': value});
	},
	
	onAskNonTargetQuestionPortletAppend: function(eventData)	{
		var txt = eventData.txt;
		var value = eventData.value;
		var topicContainer = this.requestForEffectiveResource("AddTopicContainer");
		var addTopicInputBox = this.requestForEffectiveResource("AddTopicInputBox");
		if (this.selectedTopics == undefined)
			this.selectedTopics = Array();
		for( i=0; i<this.selectedTopics.length;i++ ){
			if(this.selectedTopics[i] === value){
				return;
			}
		}
		var textToken = $("<label class='tokenContent'>"+txt+"</label>");
		this.selectedTopics.push(value);
		
		// UI ONLY
		var selectedTopics = this.selectedTopics;
		var span = $("<span>").addClass("uiToken").append(textToken);
		var a = $("<span>").addClass("btnStl").addClass("delToken").bind("click",function(event){
				var start = 0;
				for( start=0; start<selectedTopics.length; start++ ){
					if(selectedTopics[start] === value){
						break;
					}
				}
				selectedTopics.splice(start, 1);
				$(event.target).parent().remove();
			}).html("X").css("text-align","center").appendTo(span);
		topicContainer.append(span);
	},
	
	onAskNonTargetTextBoxFocus: function(eventData)	{
		this.requestForEffectiveResource("Extended").show();
	},
	
	onAskNonTargetButtonClick: function(eventData)	{
		//console.log("onAskNonTargetButtonClick");
		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
		var question = this.requestForEffectiveResource("TextBox").val();
		var extended = this.requestForEffectiveResource("TextAreaExtended").val();
		
		if (question == undefined || question.trim() == '')	{
			this.requestForEffectiveResource('QuestionError1').html('Câu hỏi không được để trống');
			return;
		}
		
		var obj = this;
		obj.requestForEffectiveResource("QuestionInfo").html("");
		obj.requestForEffectiveResource("QuestionError").html("");
		obj.requestForEffectiveResource("QuestionError1").html("");
		var selectedTopics = null;
		if(this.selectedTopics.length > 0){
			selectedTopics = new Array();
			for( var i=0; i<this.selectedTopics.length; i++ ){
				selectedTopics.push({"catchword_id":this.selectedTopics[i],"position":0}); 
			}
		}
		var target_id = undefined;
		var target_next_id = undefined;
		if (this.selectedPeople != undefined && this.selectedPeople.length > 0)	{
			target_id = this.selectedPeople[0];
			if (this.selectedPeople.length > 1)	{
				target_next_id = this.selectedPeople[1];
			}
		}
		this.onAjax('question', 'add-unauth-question', {'title': question, 'content': extended, 'catch': selectedTopics, 'target_id': target_id, 'target_next_id': target_next_id}, 'POST', 
			{'onSuccess': function(ret)	{
				this.selectedTopics = Array();
				var sbj = SingletonFactory.getInstance(Subject);
				sbj.notifyEvent("NotifyGlobal", obj.getLocalizedText("AskSuccess"));
				sbj.notifyEvent("PopupRemove", {id: 'AskNonTargetQuestion'});
			},
			'onFailure': function(message)	{
				obj.requestForEffectiveResource("QuestionError").html(obj.getLocalizedText("AskError"));
			}
		});
	}
}).implement(PortletInterface).implement(RenderInterface).implement(ObserverInterface).implement(AjaxInterface);

//QuestionAskingPortlet = Class.extend({
//	init: function()	{
//		this.name = "QuestionAskingPortlet";
//	},
//	
//	onBegin: function()	{
//		this.model = {};
//	},
//	
//	onReloadPage: function()	{
//		this.run();
//	},
//	
//	run: function()	{
//		var obj = this;
//		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
//		//FIXME: (Done) ProfileId must be retrieved from the request parameters
//		var profileId = this.getRequest().getParam('id', undefined);
//		this.onAjax('question', 'list-auth-question-by-user', {'user_id': profileId}, 'GET', 
//				{'onSuccess': function(ret)	{
//					obj.model.questionAskedTitle = "Các câu đang hỏi";
//					obj.model.questions = ret;
//					obj.getPortletPlaceholder().paintCanvas(obj.render());
//				}});
//	}
//}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface);

QuestionPendingPortlet = Class.extend({
	init: function()	{
		this.name = "QuestionPendingPortlet";
	},
	
	onReloadPage: function()	{
		this.run();
	},
	
	run: function()	{
		var obj = this;
		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
		var pendingQuestions = Array();
		var cached = SingletonFactory.getInstance(Application).getSystemProperties().get("memcached.pendingQuestions");
		this.onAjax('question', 'list-user-pending-question', {}, 'GET', 
				{'onSuccess': function(ret)	{
					obj.model = {};
					obj.model.questionPendingTitle = "Các câu hỏi đang chờ duyệt";
					obj.model.questionPendingDescription = obj.getLocalizedText('QuestionPendingDescription');
					obj.model.questions = Array();
					for (var i=0;i<ret.length;i++)	{
						var r = ret[i];
						pendingQuestions[r.id] = r;
						if (r.target_name == undefined)
							r.target_name = "";
						obj.model.questions.push(obj.getLocalizedMessage('QuestionSummary', r.target_name, r.title, $.timeFormat(r.created_date), r.id, r.id));
					}
					obj.getPortletPlaceholder().paintCanvas(obj.render());
					SingletonFactory.getInstance(Application).getSystemProperties().set("memcached.pendingQuestions",pendingQuestions);
				}});
	}
}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface);

QuestionClickPlugin = Class.extend({
	init: function()	{
		this.name = "QuestionClick";
	},
	
	onQuestionSummaryClick: function(eventData)	{
		Request.setProactive(true);
		var request = new Request("Question", undefined, {'qid': eventData});
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent("RequestRoute", request);
	}
}).implement(PluginInterface);

AutocompletePlugin = Class.extend({
	init: function()	{
		this.name = "AutocompletePlugin";
	},
	
	onNeedAutocomplete: function(eventData)	{
		//console.log('autocomplete');
		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
		var subject = SingletonFactory.getInstance(Subject);
		var url = root+eventData.autocompleteSource;
		var suggestions = Array();
		var obj = eventData.autocompleteObject;
		var type = eventData.type;
		if (type == undefined)	{
			type = 'Question';
		}
		
		if (eventData.fetchSourceCallback != undefined)
			subject.notifyEvent(eventData.fetchSourceCallback);
		$(obj).autocomplete({
			source: function(req, add){
				var term = $(obj).val();
				req.term = term;
				$.getJSON(url, req, function(data) {
					var suggestions = [];
					$.each(data['result'], function(i, val){
						if (type == 'Question')
							suggestions.push({label:val.expertise, value:val.id, type: 'expertise', follow: val.catch_follow});
						else 
							suggestions.push({label: val.person, value: val.userID, type: 'person', catchwords: val.expertises, avatar: val.avatar, ans: val.totalAns});
					});
					add(suggestions);
				});
			},
			focus:  function(e,ui){
				if (eventData.focusCallback != undefined)
					subject.notifyEvent(eventData.focusCallback, {'ui':ui});
			},
			select: function(e,ui){
				if (eventData.selectCallback != undefined)
					subject.notifyEvent(eventData.selectCallback, {'ui':ui});
			},
			result: function(e, ui)	{
				if (eventData.resultCallback != undefined)
					subject.notifyEvent(eventData.resultCallback, {'ui':ui});
			}
		});
	}
}).implement(PluginInterface);

BriefInfoPortlet = Class.extend({
	init: function()	{
		this.name = "BriefInfoPortlet";
	},
	
	onReloadPage: function()	{
		this.run();
	},
	
	run: function()	{
		this.model = {};
		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
		var obj = this;
		var props = SingletonFactory.getInstance(Application).getSystemProperties();
		var id = this.getRequest().getParam('id');
		this.onAjax('user-ajax', 'get-brief-info', {'id': id}, 'GET', {
			'onSuccess': function(ret)	{
				// basic
				var avatar = ret.avatar;
				obj.model.page = obj.getRequest().getParam('page');
				obj.model.id = id ? id: props.get('user.id');
				obj.model.name = ret.name;
				obj.model.avatar = "avatar/"+avatar;
				
				// statistic
				obj.model.answerCount = ret.answerCount;
				obj.model.questionCount = ret.questionCount;
				
				// interests
				obj.model.interestTitle = "Lĩnh vực quan tâm";
				obj.model.interestContexts = ret.interests;
				
				// catches
				obj.model.expertiseTitle = "Kinh nghiệm";
				obj.model.expertiseContexts = ret.catches;
				
				obj.getPortletPlaceholder().paintCanvas(obj.render());
			}
		});
	}
}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface);

AvatarEditPlugin = Class.extend({
	init: function()	{
		this.name = "AvatarEditPlugin";
	},
	
	onReloadPlugin: function()	{
		this.renderAvatar();
	},
	
	onAvatarInputChange: function()	{
		$('#AvatarUploaderContainer').submit();
	},
	
	renderAvatar: function()	{
		var obj = this;
		$('.extension-point[extensionName="avatar"]').each(function(index, value)	{
			if ($(value).find('div[flag="AvatarUploader"]').length>0)
				return;
			var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
			$(value).append(tmpl('AvatarUploader', {'root': root}));
			$('#AvatarUploaderContainer').submit(function() {
				var fr = $('#avatar-upload-frame');
				$(fr).one('load', function() {
					var response = fr.contents().find('body').html();
					$('AvatarUploaderContainer').find('input[type="submit"]').attr('disabled', '');
			    	var ret = $.parseJSON(response);
			    	$(value).find('#AvatarUploaderErrorPlaceholder').html('');
			    	if (ret.result == "error")	{
			    		errors = {};
			    		errors.errors = ret.message; 
			    		$(value).find('#AvatarUploaderErrorPlaceholder').html(tmpl('AvatarUploaderError', errors));
			    	} else {
			    		$('#BriefInfoEditPortlet-Avatar').find('img').remove();
			    		$('#BriefInfoEditPortlet-Avatar').html('<img style="width: 100px" src="avatar/'+ret.result+'" />');
		    			var subject = SingletonFactory.getInstance(Subject);
		    			subject.notifyEvent('NotifyGlobal', 'Bạn đã thay đổi avatar thành công. Nếu ảnh chưa hiện ra, hãy ấn F5 để thấy sự thay đổi');
			    	}
				});
			});
		});
	},
	
	onHtmlUpdated: function()	{
		this.renderAvatar();
	}
}).implement(PluginInterface);

//CredentialsEditPlugin = Class.extend({
//	init: function()	{
//		this.name = "CredentialsEditPlugin";
//	},
//
//	renderCredentialsLink: function()	{
//		var obj = this;
//		$('.extension-point[extensionName="usercpedit"]').each(function(index, value)	{
//			if ($(value).find('div[flag="UserCPEdit"]').length>0)
//				return;
//			$(value).append(tmpl('UserCP', {}));
//		});
//	},
//	
//	onProfileExpertiseEditShow: function()	{
//		$.facebox(tmpl('UserCP-EditExpertise', {}));
//		var subject = SingletonFactory.getInstance(Subject);
//		subject.notifyEvent('RenderExpertiseEditor', {namespace: 'UserCP', placeholder: $('#facebox #UserCP-ExpertisePlaceholder')});
//	},
//	
//	onSubmitExpertiseProfileButtonClick: function(eventData)	{
//		var target = eventData.target;
//		var parent = $(target).parents('#UserCP-ViewPlaceholder:first');
//		var expToSent = Array();
//		var container = $(parent).find('#UserCP-ListExpertise .tokenContainer');
//		$(container).find('label.lblToken').each(function(index, value)	{
//			var id = $(value).attr('eid');
//			expToSent.push(id);
//		});
//		
//		var intToSent = Array();
//		var container = $(parent).find('#UserCP-ListInterestedArea .tokenContainer');
//		$(container).find('label.lblToken').each(function(index, value)	{
//			var id = $(value).attr('eid');
//			intToSent.push(id);
//		});
//		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
//		intToSent = $.toJSON(intToSent);
//		expToSent = $.toJSON(expToSent);
//		var obj = this;
//		this.onAjax('ajax', 'add-expertise', {'experts': expToSent, 'interests': intToSent}, 'POST', 
//				{'onSuccess': function(ret)	{
//					obj.finishSubmitting();
//				}});
//	},
//	
//	finishSubmitting: function()	{
//		$.facebox.close();
//	},
//	
//	onHtmlUpdated: function()	{
//		this.renderCredentialsLink();
//	}
//}).implement(PluginInterface).implement(AjaxInterface);

ProfileNameEditPlugin = Class.extend({
	init: function()	{
		this.name = "ProfileNameEditPlugin";
	},
	
	saveData: function(event)	{
		var target = event.target;
		var newValue = $(target).val().trim();
		var oldValue = $(target).attr('oldValue');
		if (newValue == "")	{
			newValue = oldValue;
		}
		$(target).parent().removeAttr('editing');
		$(target).parent().html(newValue);
		if (oldValue != newValue)	{
			this.onAjax('user-ajax', 'edit-name', {'name': newValue}, 'POST', {});
		}
	},
	
	onProfileEditOnBlur: function(event)	{
		this.saveData(event);
	},
	
	onProfileEditOnKeyup: function(event)	{
		var keycode = event.keyCode;
		if (keycode == 13)	{
			this.saveData(event);
		}
	},
	
	onProfileNameEditClick: function(event)	{
		var target = event.target;
		var editTarget = $(target).parent().siblings('#BriefInfoEditPortlet-ProfileName');
		if ($(editTarget).attr('editing') == 'editing')
			return;
		var old = $(editTarget).html();
		$(editTarget).attr('editing', 'editing');
		$(editTarget).html('<input oldValue="'+old+'" onkeyup="generateEvent(&apos;ProfileEditOnKeyup&apos;, event)" onblur="generateEvent(&apos;ProfileEditOnBlur&apos;, event)" value="'+old+'">');
		$(editTarget).find('input').focus();
	},

	renderEditLink: function()	{
		var obj = this;
		$('.extension-point[extensionName="ProfileName"]').each(function(index, value)	{
			if ($(value).find('div[flag="ProfileNameEdit"]').length>0)
				return;
			$(value).append(tmpl('ProfileNameEdit', {}));
		});
	},
	
	onHtmlUpdated: function()	{
		this.renderEditLink();
	}
}).implement(PluginInterface).implement(AjaxInterface);

//ShowTopicCreatePopupPlugin = Class.extend({
//	init: function()	{
//		this.name = "ShowTopicCreatePopupPlugin";
//	},
//	
//	onShowTopicCreatePopup: function(eventData)	{
//		var cb = eventData.callback;
//		var cmcb = eventData.commitcallback;
//		var w = 600;
//		var h = 400;
//		var left = (screen.width/2)-(w/2);
//		var top = (screen.height/2)-(h/2);
//		window.open('#page/TopicCreatePagePopup/callback/'+cb+'/commit-callback/'+cmcb, 'topicCreateWindow', "status = 0, height = "+h+", width = "+w+", resizable = 1, left = "+left+", top = "+top);
//	}
//}).implement(PluginInterface);

ExpertiseAdderPortlet = Class.extend({
	init: function()	{
		this.name = "ExpertiseAdderPortlet";
	},
	
	onBegin: function()	{
		this.registerObserver();
	},
	
	onSubmitExpertiseAdderButtonClick: function()	{
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('SubmitExpertiseForward', {callback: function()	{
			subject.notifyEvent('NotifyGlobal', 'Đã thêm thành công');
		}, namespace: this.name});
	},
	
	run: function()	{
		this.getPortletPlaceholder().paintCanvas(this.render());
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('RenderExpertiseEditor', {placeholder:this.requestForEffectiveResource('ExpertisePlaceholder'), namespace: this.name});
	},
	
	onEnd: function()	{
		this.unregisterObserver();
	}
}).implement(PortletInterface).implement(RenderInterface).implement(ObserverInterface);

InterestAdderPortlet = Class.extend({
	init: function()	{
		this.name = "InterestAdderPortlet";
	},
	
	onBegin: function()	{
		this.registerObserver();
	},
	
	onSubmitInterestAdderButtonClick: function()	{
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('SubmitInterestForward', {callback: function()	{
			subject.notifyEvent('NotifyGlobal', 'Đã thêm thành công');
		}, namespace: this.name});
	},
	
	run: function()	{
		this.getPortletPlaceholder().paintCanvas(this.render());
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('RenderInterestEditor', {placeholder:this.requestForEffectiveResource('ExpertisePlaceholder'), namespace: this.name});
	},
	
	onEnd: function()	{
		this.unregisterObserver();
	}
}).implement(PortletInterface).implement(RenderInterface).implement(ObserverInterface);

BasicInfoEditPortlet = Class.extend({
	init: function()	{
		this.name = "BasicInfoEditPortlet";
		this.subject = SingletonFactory.getInstance(Subject);
	},
	
	run: function()	{
		this.getPortletPlaceholder().paintCanvas(this.render());
		this.subject.notifyEvent('DisplayRemainingNodes', {'id': this.name});
		this.subject.notifyEvent('NeedFormatting');
		this.subject.notifyEvent("ProfileInputBindEvent");
	},
	
	onSubmitEditBasicInfoButtonClick: function()	{
		
	}
}).implement(PortletInterface).implement(RenderInterface);